// 工具函数库
import config from './config'

// http get工具函数 获取数据
export function get (url, data) {
  return request(url, 'GET', data)
}
export function post (url, data) {
  return request(url, 'POST', data)
}

function request (url, method, data, header = {}) {
  return new Promise((resolve, reject) => {
    wx.request({
      data,
      method,
      header,
      url: config.host + url,
      success: function (res) {
        if (res.data.code === 0) {
          resolve(res.data.data)
        } else {
          showModal('失败', res.data.data.msg)
          reject(res.data)
        }
      }
    })
  })
}

export function showModal (title, content) {
  wx.showModal({
    title,
    content,
    showCancel: false
  })
}
export function showSuccess (text) {
  wx.showToast({
    title: text,
    icon: 'success'
  })
}
// 字符串转成包含该元素的数组
function transToTableParam (el) {
  for (let f in el) {
    let data = el[f]
    if (Array.isArray(data)) {
      for (let i in data) {
        if (typeof data[i] === 'string') {
          data[i] = [data[i]]
        }
      }
    }
  }
}
export function transTblParam (data) {
  return transToTableParam(data)
}

export function transWeaponGui (data) {
  return transWeapon(data)
}

// json数组转换成图形对象
function transWeapon (data) {
  data.forEach((item, i) => {
    turnSelf(item)
    changeSlib(data, i)
  })
  console.log(data)
}

function turnSelf (data) {
  data.nodes = []
  if (data.level === 1) {
    data.nodes.push('D')
  } else {
    for (let i = 2; i < data.level; i++) {
      data.nodes.push(' ')
    }
    data.nodes.push('L')
    data.nodes.push('D')
  }
}

/**
 * 0:表示空格 1：表示转折 2.表示数据 3.表示连线
 */
function changeSlib (data, i) {
  let item = data[i]
  // 查找父节点或兄弟节点索引
  if (item.level !== 1 && data[i - 1].level !== (item.level - 1)) { // 非第一个子节点
    let siblingIndex = 0
    // 查找兄弟结点
    for (let k = 1; k < i; k++) {
      if (data[k].level === data[i].level) {
        siblingIndex = k
      }
    }
    // 十字线
    data[siblingIndex].nodes[item.level - 2] = '+'
    // 兄弟节点间补充
    for (siblingIndex = siblingIndex + 1; siblingIndex < i; siblingIndex++) {
      data[siblingIndex].nodes[item.level - 2] = '|'
    }
  }
}
